package com.agilya.controller;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.agilya.utilitaires.Configuration;

/**
 * Servlet implementation class AfficherImage
 * 
 * Permet d'afficher une image hors du contexte grâce à sa source passée en paramètre
 * 
 */
@WebServlet("/AfficherImage")
public class AfficherImage extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AfficherImage() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// on récupère la source de l'image
		try {
			String src = (String) request.getParameter("src");

			// On récupère l'image
			FileInputStream imageStream = new FileInputStream(Configuration.getAbsolutePathDossierUploadImage(request) + src);
			byte buffer[] = new byte[1024];

			int n;
			while ((n = imageStream.read(buffer)) != -1) {
				response.getOutputStream().write(buffer, 0, n);
			}
		} catch (Exception e) {
			request.setAttribute("erreurPage", "Impossible de charger l'image");
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// NOTHING
	}

}
